<script lang="ts">
export default {
  options: {
    virtualHost: true, // 虚拟节点
    styleIsolation: 'shared', // 解除样式隔离
  },
}
</script>

<script setup lang="ts">
defineOptions({ name: 'ProPicker' })

const props = withDefaults(defineProps<{
  modelValue: string | number | null
  code?: string
  options?: Array<any>
  selectFirst?: boolean
  placeholder?: string
}>(), {
  modelValue: null,
  code: undefined,
  options: undefined,
  selectFirst: false,
  placeholder: '请选择',
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: string | number): void
  (e: 'change', value: string | number): void
}>()

const dictOptions = useDictOptions(props.code)
const pickerOptions = computed(() => {
  if (props.code) {
    return dictOptions.value
  } else {
    return props.options?.map((item) => {
      return { label: item.label || item.name, value: item.id }
    })
  }
})

const index = ref(-1)
const onChange = (e) => {
  index.value = e.detail.value
  const selectedOption = pickerOptions.value[index.value]
  emit('update:modelValue', selectedOption.value)
  emit('change', selectedOption.value)
}
watchEffect(() => {
  if (!props.modelValue && props.selectFirst && pickerOptions.value.length > 0) {
    index.value = 0
    emit('update:modelValue', pickerOptions.value[0].value)
    emit('change', index.value)
  } else {
    index.value = pickerOptions.value.findIndex((item) => {
      return item.value === props.modelValue
    })
  }
})
</script>

<template>
  <picker :value="index" :range="pickerOptions" range-key="label" @change="onChange">
    <view class="flex items-center gap-1 line-1">
      <view>{{ index >= 0 ? pickerOptions[index].label : placeholder }}</view>
      <slot />
    </view>
  </picker>
</template>

<style scoped>

</style>
